﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using ScanningGunModel;
using System.IO.Ports;
using ActUtlTypeLib;
using PylonCamera;
using System.Web;
using System.Web.Services;
using Commonality.DAL.MySQL;
using System.Text.RegularExpressions;

namespace WZS_Package
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.WindowState = FormWindowState.Maximized;
            hv_win1 = hWindowControl1.HalconWindow;
            hv_win2 = hWindowControl2.HalconWindow;
            HOperatorSet.SetPart(hv_win1, 0, 0, 3036 - 1, 4024 - 1);
            HOperatorSet.SetPart(hv_win2, 0, 0, 3036 - 1, 4024 - 1);

            HObject empty_image;             //开始运行时显示一张空照片，不然halcon会有bug
            HOperatorSet.GenEmptyObj(out empty_image);
            empty_image.Dispose();
            HOperatorSet.ReadImage(out empty_image, Application.StartupPath + "\\Tool\\Empty.bmp");
            HOperatorSet.DispObj(empty_image, hv_win1);
            HOperatorSet.DispObj(empty_image, hv_win2);
            empty_image.Dispose();

        }

        CKeyenceScanningGunModel KeyenceScanningGunModel_1, KeyenceScanningGunModel_2, KeyenceScanningGunModel_3, KeyenceScanningGunModel_4, KeyenceScanningGunModel_5;
        CKeyenceScanningGunModel KeyenceScanningGunModel_6;   //称重处扫码枪
        static CPylonCamera Camera1 = new CPylonCamera();  //前相机
        static CPylonCamera Camera2 = new CPylonCamera();  //后相继

        ComPortCommunication Scales1 = new ComPortCommunication();   //前电子秤
        ComPortCommunication Scales2 = new ComPortCommunication();   //后电子秤
        ComPortCommunication Scanner_Box_Confirm = new ComPortCommunication();   //箱子校验扫码枪
        

        ActUtlTypeLib.ActUtlType plc1 = new ActUtlType();   //线体plc
        ActUtlTypeLib.ActUtlType plc2 = new ActUtlType();  //机器人侧plc
        ActUtlTypeLib.ActUtlType plc3 = new ActUtlType();  //包装侧plc

        public int[] Product_Num = {0,0,0,0,0,0,0,0,0,0,0,0};  //OK数，有异物,条码ng，站别错误，被hold，混料，重量异常，没checkout,库类错误,CQA BL是否NG,X17_Tilt_NG

        public WZS_SFCS.WebService Mes = new WZS_SFCS.WebService();

        HTuple hv_win1, hv_win2;

        public string last_note = "";           //保存上一日志，防止重复打印相同日志
        public string last_note1 = "";
        TxtHelper txthelper = new TxtHelper();
        TxtHelper txthelper2 = new TxtHelper();

        public Thread Auto_Thread;//自动运行线程
        public bool b_auto_thread;//线程循环条件

        public Thread T_Entrance_Scan; //入口处扫描线程
        public Thread T_Detection;   //异物检测线程
        public Thread T_Seperate_Scan; //分板扫码线程
        public Thread T_Front_Weighing;  //前端称重线程
        public Thread T_Export_Scan;   //出口处扫码线程
        public Thread T_Final_Weighing;  //最终称重线程
        public Thread T1, T2;
        public Thread T_Check_Box_Label;  //检测箱子上有无贴label

        System.Windows.Forms.Timer Scanner_Confirm_T;

        public string str_scanner1code,str_scanner2code,str_scanner3code,str_scanner4code, str_scanner5code, str_scanner6code;//扫码枪返回值

        public string str_weight1, str_weight2;  //电子秤数值

        public HObject m_image1, m_image2;

        public List<string> result_type = new List<string>();  //人工段产品记录产品类型序列
        public List<string> result_detection = new List<string>();  //人工段产品异物检测结果序列
        public List<string> result_code = new List<string>();  //人工段产品扫码结果序列
        public List<string> result_weight = new List<string>();  //人工段产品称重结果序列
        public List<string> result_type_out = new List<string>();  //排料口处记录产品类型序列

        //序列转成字符串保存到ini
        public string str_result_type, str_result_detection, str_result_code, str_result_weight, str_result_type_out; 

        public string In0;  //入料口扫码
        public string In1;  //异物检测
        public string In2;  //分板扫码
        public string In3;  //自动段来料称总重
        public string In4;  //人工段来料分板称重
        public string In5;  //出料口扫码
        public string In6;  //末端称总重
        public string In7;  //人工段来料分板数量
        public string In8;  //清计数
        public string In9;  //拍照处机种读取
        public string Out0;  //入料口扫码完成
        public string Out1;  //异物检测完成
        public string Out2;  //分板扫码完成
        public string Out3;  //自动段来料称总重完成
        public string Out4;  //人工段来料分板称重完成
        public string Out5;  //出料口扫码完成
        public string Out6;  //末端称总重完成
        public string Out7;  //盖板分类
        public string Out8;  //未满箱是否包装，0 不包   1 包
        public string Out6Redundancy; //Out6的冗余

        public string FATP_UserID,Weight_UserID,StationPP,StationPO;  //MES  ID

        public string POut1;  //包装侧PLC 给箱子种类   小箱子11 ,大箱子22
        public string POut2;  //绿灯
        public string POut3;  //红灯
        public string POut4;  //箱子降下去后label检测有无
        public string PIn1;   //箱子降下去后label检测有无

        public string Mark_Weight = "Ready";   //称总重标志位
        public string Mark_BoxConfirm = "Ready";  //箱子校验标志

        public double row, col, phi, lenth1, lenth2, threshold, minarea;  //视觉检测参数
        private double row1Card1, col1Card1, row2Card1, col2Card1, minareaCard1, maxareaCard1;
        private double row1Card2, col1Card2, row2Card2, col2Card2, minareaCard2, maxareaCard2;
        public bool isCaer;

        public string Out_Type;   //正在包装的类型

        //扫码枪超时时间
        public static long SG1TimeOut = 1000;
        public static long SG2TimeOut = 1000;
        public static long SG3TimeOut = 1000;
        public static long SG4TimeOut = 1000;
        public static long SG5TimeOut = 1000;
        public static long SG6TimeOut = 1000;

        /// <summary>
        /// 被标记的MO
        /// </summary>
        public static List<string> Mo = new List<string>();
        public static string parameterFeilName = Application.StartupPath + @"\Tool\Parameter.xml";

        private void Form1_Load(object sender, EventArgs e)
        {
            MySqlFunction.InitMySQLFunction();
            DeviceInfoIni();
            ScannerIni();
            CameraIni();
            ScalesIni();
            PlcIni();
            InfoIni();

            cb_clearresult.SelectedIndex = 0;
            cb_plc.SelectedIndex = 0;
            cb_packagemode.SelectedIndex = 0;
            cb_mode.SelectedIndex = 1;


            Auto_Thread = new Thread(new ThreadStart(Auto));
            Auto_Thread.Start();
            Scanner_Confirm_T = new System.Windows.Forms.Timer();
            Scanner_Confirm_T.Interval = 2000;
            Scanner_Confirm_T.Start();
            Scanner_Confirm_T.Tick += Box_Confirm;

            MoBasicVectorLoad();
            MoBasicVectorDisplay();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            OperateIniFile.WriteIniData("Device", "typeX01", tb_typeX01.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX03", tb_typeX03.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX05", tb_typeX05.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX08", tb_typeX08.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX13", tb_typeX13.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX15", tb_typeX15.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX176", tb_typeX176.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX177", tb_typeX177.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX178", tb_typeX178.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "typeX19", tb_typeX19.Text, Application.StartupPath + @"\Tool\Device.ini");

            OperateIniFile.WriteIniData("Device", "storage1", cb_storage1.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "storage2", cb_storage2.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "storage3", cb_storage3.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "storage4", cb_storage4.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "storage5", cb_storage5.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "storage6", cb_storage6.SelectedIndex.ToString(), Application.StartupPath + @"\Tool\Device.ini");

            OperateIniFile.WriteIniData("Device", "SGTimeOut1", SG1TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "SGTimeOut2", SG2TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "SGTimeOut3", SG3TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "SGTimeOut4", SG4TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "SGTimeOut5", SG5TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "SGTimeOut6", SG6TimeOut_textBox.Text.ToString(), Application.StartupPath + @"\Tool\Device.ini");


            OperateIniFile.WriteIniData("Device", "tb_singleweight1min", tb_singleweight1min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweight1max", tb_singleweight1max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweight2min", tb_singleweight2min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweight2max", tb_singleweight2max.Text, Application.StartupPath + @"\Tool\Device.ini");

            OperateIniFile.WriteIniData("Device", "tb_singleweightX3min", tb_singleweightX3min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX3max", tb_singleweightX3max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX5min", tb_singleweightX5min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX5max", tb_singleweightX5max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX8min", tb_singleweightX8min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX8max", tb_singleweightX8max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX15min", tb_singleweightX15min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX15max", tb_singleweightX15max.Text, Application.StartupPath + @"\Tool\Device.ini");

            OperateIniFile.WriteIniData("Device", "tb_singleweightX176min", tb_singleweightX176min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX176max", tb_singleweightX176max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX177min", tb_singleweightX177min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX177max", tb_singleweightX177max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX178min", tb_singleweightX178min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX178max", tb_singleweightX178max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX19min", tb_singleweightX19min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_singleweightX19max", tb_singleweightX19max.Text, Application.StartupPath + @"\Tool\Device.ini");

            OperateIniFile.WriteIniData("Device", "tb_X1min", tb_X1min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X1max", tb_X1max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X3min", tb_X3min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X3max", tb_X3max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X5min", tb_X5min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X5max", tb_X5max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X8min", tb_X8min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X8max", tb_X8max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X13min", tb_X13min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X13max", tb_X13max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X15min", tb_X15min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X15max", tb_X15max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X176min", tb_X176min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X176max", tb_X176max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X177min", tb_X177min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X177max", tb_X177max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X178min", tb_X178min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X178max", tb_X178max.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X19min", tb_X19min.Text, Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X19max", tb_X19max.Text, Application.StartupPath + @"\Tool\Device.ini");


            OperateIniFile.WriteIniData("Device", "tb_X13Box", (checkBox_X13.Checked?1:0).ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X176Box", (checkBox_X176.Checked ? 1 : 0).ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X177Box", (checkBox_X177.Checked ? 1 : 0).ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X178Box", (checkBox_X178.Checked ? 1 : 0).ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_X19Box", (checkBox_X19.Checked ? 1 : 0).ToString(), Application.StartupPath + @"\Tool\Device.ini");
            OperateIniFile.WriteIniData("Device", "tb_SmallBox", (checkBox_Small.Checked ? 1 : 0).ToString(), Application.StartupPath + @"\Tool\Device.ini");

            b_auto_thread = false;
            Thread.Sleep(100);
            Auto_Thread.Abort();

            try
            {
                T_Final_Weighing.Abort();
                T_Entrance_Scan.Abort();
                T_Detection.Abort();
                T_Seperate_Scan.Abort();
                T_Front_Weighing.Abort();
                T_Export_Scan.Abort();
                T_Check_Box_Label.Abort();
            }
            catch
            {

            }
            InsertNote("关闭软件", listBox1);
            Camera1.CameraClose();
            //Camera2.CameraClose();
            //Scales1.ComPortClose();
            //Scales2.ComPortClose();
            plc1.Close();
            plc2.Close();
            plc3.Close();
        }

        private void PlcIni()   //plc初始化
        {
            plc1.ActLogicalStationNumber = 1;
            plc2.ActLogicalStationNumber = 2;
            plc3.ActLogicalStationNumber = 3;

            int ret1 = plc1.Open();
            int ret2 = plc2.Open();
            int ret3 = plc3.Open();
            if (ret1==0&&ret2==0&&ret3==0)
            {
                toolstrip_plc.BackColor = Color.Green;
                InsertNote("PLC连接成功",listBox1);
            }
            else
            {
                toolstrip_plc.BackColor = Color.Crimson;
                InsertNote("PLC连接失败", listBox1);
            }
        }

        private void CameraIni()  //相机初始化
        {
            String cam1 = OperateIniFile.ReadIniData("Device", "Cam1", "", Application.StartupPath + @"\Tool\Device.ini");
            String cam2 = OperateIniFile.ReadIniData("Device", "Cam2", "", Application.StartupPath + @"\Tool\Device.ini");
            String cam1Expo = OperateIniFile.ReadIniData("Device", "Cam1Exposure", "", Application.StartupPath + @"\Tool\Device.ini");
            String cam2Expo = OperateIniFile.ReadIniData("Device", "Cam2Exposure", "", Application.StartupPath + @"\Tool\Device.ini");

            bool ret1 = false;
            try
            {
               ret1 = Camera1.OpenCamera(cam1);
            }
            catch
            {

            }
            //bool ret2 = Camera2.OpenCamera("Camera2");
            if (ret1)
            {
                bool a = Camera1.SetExposureTimeAbs(Convert.ToDouble(cam1Expo));
                toolstrip_cam.BackColor = Color.Green;
                InsertNote("相机初始化成功", listBox1);
            }
            else
            {
                toolstrip_cam.BackColor = Color.Crimson;
                InsertNote("相机初始化失败", listBox1);

            }
        }

        private void ScalesIni()   //电子秤初始化
        {
            Scales1.ComPortOpen("COM5", 9600);
            Scales2.ComPortOpen("COM6", 9600);
        }

        private void ScannerIni()  //扫码枪初始化
        {
            try
            {
                //配置扫码枪和注册返回值回调函数
                KeyenceScanningGunModel_1 = new CKeyenceScanningGunModel("COM1", 115200, 8, Parity.None, StopBits.One, QRcodeCallback1);
                KeyenceScanningGunModel_2 = new CKeyenceScanningGunModel("COM2", 115200, 8, Parity.None, StopBits.One, QRcodeCallback2);
                KeyenceScanningGunModel_3 = new CKeyenceScanningGunModel("COM3", 115200, 8, Parity.None, StopBits.One, QRcodeCallback3);
                KeyenceScanningGunModel_4 = new CKeyenceScanningGunModel("COM4", 115200, 8, Parity.None, StopBits.One, QRcodeCallback4);
                KeyenceScanningGunModel_5 = new CKeyenceScanningGunModel("COM7", 115200, 8, Parity.None, StopBits.One, QRcodeCallback5);
                KeyenceScanningGunModel_6 = new CKeyenceScanningGunModel("COM9", 115200, 8, Parity.None, StopBits.One, QRcodeCallback6);

                //扫码枪超时时间
                SG1TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut1", "", Application.StartupPath + @"\Tool\Device.ini"));
                SG2TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut2", "", Application.StartupPath + @"\Tool\Device.ini"));
                SG3TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut3", "", Application.StartupPath + @"\Tool\Device.ini"));
                SG4TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut4", "", Application.StartupPath + @"\Tool\Device.ini"));
                SG5TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut5", "", Application.StartupPath + @"\Tool\Device.ini"));
                SG6TimeOut = Convert.ToInt64(OperateIniFile.ReadIniData("Device", "SGTimeOut6", "", Application.StartupPath + @"\Tool\Device.ini"));

                Console.WriteLine("扫码超时时间：" + SG1TimeOut.ToString());
                Console.WriteLine("扫码超时时间：" + SG2TimeOut.ToString());
                Console.WriteLine("扫码超时时间：" + SG3TimeOut.ToString());
                Console.WriteLine("扫码超时时间：" + SG4TimeOut.ToString());
                Console.WriteLine("扫码超时时间：" + SG5TimeOut.ToString());
                Console.WriteLine("扫码超时时间：" + SG6TimeOut.ToString());

            }
            catch
            {

            }
            Scanner_Box_Confirm.ComPortOpen("COM8", 115200);
        }

        private void InfoIni()  //在籍信息导入
        {
            str_result_detection = OperateIniFile.ReadIniData("在籍", "detection", "", Application.StartupPath + @"\Tool\Setting.ini");
            result_detection = str_result_detection.Split(',').ToList();
            result_detection.Remove("");
            str_result_code = OperateIniFile.ReadIniData("在籍", "code", "", Application.StartupPath + @"\Tool\Setting.ini");
            result_code = str_result_code.Split(',').ToList();
            result_code.Remove("");
            str_result_type = OperateIniFile.ReadIniData("在籍", "type", "", Application.StartupPath + @"\Tool\Setting.ini");
            result_type = str_result_type.Split(',').ToList();
            result_type.Remove("");
            str_result_weight = OperateIniFile.ReadIniData("在籍", "weight", "", Application.StartupPath + @"\Tool\Setting.ini");
            result_weight = str_result_weight.Split(',').ToList();
            result_weight.Remove("");
            str_result_type_out = OperateIniFile.ReadIniData("在籍", "type_out", "", Application.StartupPath + @"\Tool\Setting.ini");
            result_type_out = str_result_type_out.Split(';').ToList();
            result_type_out.Remove("");
            string pd_num = OperateIniFile.ReadIniData("在籍", "Product_Num", "", Application.StartupPath + @"\Tool\Setting.ini");
            try
            {
                Product_Num[0] = Convert.ToInt16(pd_num.Split(',')[0]);
                Product_Num[1] = Convert.ToInt16(pd_num.Split(',')[1]);
                Product_Num[2] = Convert.ToInt16(pd_num.Split(',')[2]);
                Product_Num[3] = Convert.ToInt16(pd_num.Split(',')[3]);
                Product_Num[4] = Convert.ToInt16(pd_num.Split(',')[4]);
                Product_Num[5] = Convert.ToInt16(pd_num.Split(',')[5]);
                Product_Num[6] = Convert.ToInt16(pd_num.Split(',')[6]);
                Product_Num[7] = Convert.ToInt16(pd_num.Split(',')[7]);
                Product_Num[8] = Convert.ToInt16(pd_num.Split(',')[8]);
                Product_Num[9] = Convert.ToInt16(pd_num.Split(',')[9]);
                Product_Num[10] = Convert.ToInt16(pd_num.Split(',')[10]);
                Product_Num[11] = Convert.ToInt16(pd_num.Split(',')[11]);
            }
            catch
            {

            }

        }

        private void DeviceInfoIni()
        {
            In0 = OperateIniFile.ReadIniData("Device", "In0", "", Application.StartupPath + @"\Tool\Device.ini");
            In1 = OperateIniFile.ReadIniData("Device", "In1", "", Application.StartupPath + @"\Tool\Device.ini");
            In2 = OperateIniFile.ReadIniData("Device", "In2", "", Application.StartupPath + @"\Tool\Device.ini");
            In3 = OperateIniFile.ReadIniData("Device", "In3", "", Application.StartupPath + @"\Tool\Device.ini");
            In4 = OperateIniFile.ReadIniData("Device", "In4", "", Application.StartupPath + @"\Tool\Device.ini");
            In5 = OperateIniFile.ReadIniData("Device", "In5", "", Application.StartupPath + @"\Tool\Device.ini");
            In6 = OperateIniFile.ReadIniData("Device", "In6", "", Application.StartupPath + @"\Tool\Device.ini");
            In7 = OperateIniFile.ReadIniData("Device", "In7", "", Application.StartupPath + @"\Tool\Device.ini");
            In8 = OperateIniFile.ReadIniData("Device", "In8", "", Application.StartupPath + @"\Tool\Device.ini");
            In9 = OperateIniFile.ReadIniData("Device", "In9", "", Application.StartupPath + @"\Tool\Device.ini");
            Out0 = OperateIniFile.ReadIniData("Device", "Out0", "", Application.StartupPath + @"\Tool\Device.ini");
            Out1 = OperateIniFile.ReadIniData("Device", "Out1", "", Application.StartupPath + @"\Tool\Device.ini");
            Out2 = OperateIniFile.ReadIniData("Device", "Out2", "", Application.StartupPath + @"\Tool\Device.ini");
            Out3 = OperateIniFile.ReadIniData("Device", "Out3", "", Application.StartupPath + @"\Tool\Device.ini");
            Out4 = OperateIniFile.ReadIniData("Device", "Out4", "", Application.StartupPath + @"\Tool\Device.ini");
            Out5 = OperateIniFile.ReadIniData("Device", "Out5", "", Application.StartupPath + @"\Tool\Device.ini");
            Out6 = OperateIniFile.ReadIniData("Device", "Out6", "", Application.StartupPath + @"\Tool\Device.ini");
            Out7 = OperateIniFile.ReadIniData("Device", "Out7", "", Application.StartupPath + @"\Tool\Device.ini");
            Out8 = OperateIniFile.ReadIniData("Device", "Out8", "", Application.StartupPath + @"\Tool\Device.ini");
            Out6Redundancy = OperateIniFile.ReadIniData("Device", "Out6Redundancy", "", Application.StartupPath + @"\Tool\Device.ini");

            cb_storage1.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage1", "", Application.StartupPath + @"\Tool\Device.ini"));
            cb_storage2.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage2", "", Application.StartupPath + @"\Tool\Device.ini"));
            cb_storage3.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage3", "", Application.StartupPath + @"\Tool\Device.ini"));
            cb_storage4.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage4", "", Application.StartupPath + @"\Tool\Device.ini"));
            cb_storage5.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage5", "", Application.StartupPath + @"\Tool\Device.ini"));
            cb_storage6.SelectedIndex = Convert.ToInt16(OperateIniFile.ReadIniData("Device", "storage6", "", Application.StartupPath + @"\Tool\Device.ini"));

            SG1TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut1", "", Application.StartupPath + @"\Tool\Device.ini");
            SG2TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut2", "", Application.StartupPath + @"\Tool\Device.ini");
            SG3TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut3", "", Application.StartupPath + @"\Tool\Device.ini");
            SG4TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut4", "", Application.StartupPath + @"\Tool\Device.ini");
            SG5TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut5", "", Application.StartupPath + @"\Tool\Device.ini");
            SG6TimeOut_textBox.Text = OperateIniFile.ReadIniData("Device", "SGTimeOut6", "", Application.StartupPath + @"\Tool\Device.ini");

            tb_typeX01.Text = OperateIniFile.ReadIniData("Device", "typeX01", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX03.Text = OperateIniFile.ReadIniData("Device", "typeX03", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX05.Text = OperateIniFile.ReadIniData("Device", "typeX05", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX08.Text = OperateIniFile.ReadIniData("Device", "typeX08", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX13.Text = OperateIniFile.ReadIniData("Device", "typeX13", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX15.Text = OperateIniFile.ReadIniData("Device", "typeX15", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX176.Text = OperateIniFile.ReadIniData("Device", "typeX176", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX177.Text = OperateIniFile.ReadIniData("Device", "typeX177", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX178.Text = OperateIniFile.ReadIniData("Device", "typeX178", "", Application.StartupPath + @"\Tool\Device.ini");
            tb_typeX19.Text = OperateIniFile.ReadIniData("Device", "typeX19", "", Application.StartupPath + @"\Tool\Device.ini");

            POut1 = OperateIniFile.ReadIniData("Device", "POut1", "", Application.StartupPath + @"\Tool\Device.ini");
            POut2 = OperateIniFile.ReadIniData("Device", "POut2", "", Application.StartupPath + @"\Tool\Device.ini");
            POut3 = OperateIniFile.ReadIniData("Device", "POut3", "", Application.StartupPath + @"\Tool\Device.ini");
            POut4 = OperateIniFile.ReadIniData("Device", "POut4", "", Application.StartupPath + @"\Tool\Device.ini");
            PIn1 = OperateIniFile.ReadIniData("Device", "PIn1", "", Application.StartupPath + @"\Tool\Device.ini");


            FATP_UserID = OperateIniFile.ReadIniData("Device", "FATP_UserID", "", Application.StartupPath + @"\Tool\Device.ini");
            Weight_UserID = OperateIniFile.ReadIniData("Device", "Weight_UserID", "", Application.StartupPath + @"\Tool\Device.ini");
            StationPP = OperateIniFile.ReadIniData("Device", "StationPP", "", Application.StartupPath + @"\Tool\Device.ini");
            StationPO = OperateIniFile.ReadIniData("Device", "StationPO", "", Application.StartupPath + @"\Tool\Device.ini");


            row = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "row", "", Application.StartupPath + @"\Tool\Device.ini"));
            col = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "col", "", Application.StartupPath + @"\Tool\Device.ini"));
            phi = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "phi", "", Application.StartupPath + @"\Tool\Device.ini"));
            lenth1 = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "lenth1", "", Application.StartupPath + @"\Tool\Device.ini"));
            lenth2 = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "lenth2", "", Application.StartupPath + @"\Tool\Device.ini"));
            threshold = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "threshold", "", Application.StartupPath + @"\Tool\Device.ini"));
            minarea = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "minarea", "", Application.StartupPath + @"\Tool\Device.ini"));

            try
            {
                row1Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "row1", "", Application.StartupPath + @"\Tool\Device.ini"));
                col1Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "col1", "", Application.StartupPath + @"\Tool\Device.ini"));
                row2Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "row2", "", Application.StartupPath + @"\Tool\Device.ini"));
                col2Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "col2", "", Application.StartupPath + @"\Tool\Device.ini"));
                minareaCard1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "minarea", "", Application.StartupPath + @"\Tool\Device.ini"));
                maxareaCard1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "maxarea", "", Application.StartupPath + @"\Tool\Device.ini"));

                row1Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "row1", "", Application.StartupPath + @"\Tool\Device.ini"));
                col1Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "col1", "", Application.StartupPath + @"\Tool\Device.ini"));
                row2Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "row2", "", Application.StartupPath + @"\Tool\Device.ini"));
                col2Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "col2", "", Application.StartupPath + @"\Tool\Device.ini"));
                minareaCard2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "minarea", "", Application.StartupPath + @"\Tool\Device.ini"));
                maxareaCard2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "maxarea", "", Application.StartupPath + @"\Tool\Device.ini"));
            }
            catch 
            {
            }



            try
            {
                tb_singleweight1min.Text= OperateIniFile.ReadIniData("Device", "tb_singleweight1min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweight1max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweight1max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweight2min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweight2min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweight2max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweight2max", "", Application.StartupPath + @"\Tool\Device.ini");

                tb_singleweightX3min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX3min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX3max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX3max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX5min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX5min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX5max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX5max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX8min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX8min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX8max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX8max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX15min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX15min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX15max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX15max", "", Application.StartupPath + @"\Tool\Device.ini");

                tb_singleweightX176min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX176min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX176max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX176max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX177min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX177min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX177max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX177max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX178min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX178min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX178max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX178max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX19min.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX19min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_singleweightX19max.Text = OperateIniFile.ReadIniData("Device", "tb_singleweightX19max", "", Application.StartupPath + @"\Tool\Device.ini");

                tb_X1min.Text = OperateIniFile.ReadIniData("Device", "tb_X1min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X1max.Text = OperateIniFile.ReadIniData("Device", "tb_X1max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X3min.Text = OperateIniFile.ReadIniData("Device", "tb_X3min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X3max.Text = OperateIniFile.ReadIniData("Device", "tb_X3max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X5min.Text = OperateIniFile.ReadIniData("Device", "tb_X5min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X5max.Text = OperateIniFile.ReadIniData("Device", "tb_X5max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X8min.Text = OperateIniFile.ReadIniData("Device", "tb_X8min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X8max.Text = OperateIniFile.ReadIniData("Device", "tb_X8max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X13min.Text = OperateIniFile.ReadIniData("Device", "tb_X13min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X13max.Text = OperateIniFile.ReadIniData("Device", "tb_X13max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X15min.Text = OperateIniFile.ReadIniData("Device", "tb_X15min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X15max.Text = OperateIniFile.ReadIniData("Device", "tb_X15max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X176min.Text = OperateIniFile.ReadIniData("Device", "tb_X176min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X176max.Text = OperateIniFile.ReadIniData("Device", "tb_X176max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X177min.Text = OperateIniFile.ReadIniData("Device", "tb_X177min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X177max.Text = OperateIniFile.ReadIniData("Device", "tb_X177max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X178min.Text = OperateIniFile.ReadIniData("Device", "tb_X178min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X178max.Text = OperateIniFile.ReadIniData("Device", "tb_X178max", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X19min.Text = OperateIniFile.ReadIniData("Device", "tb_X19min", "", Application.StartupPath + @"\Tool\Device.ini");
                tb_X19max.Text = OperateIniFile.ReadIniData("Device", "tb_X19max", "", Application.StartupPath + @"\Tool\Device.ini");

            }
            catch
            {

            }


            if (In0=="D300")
            {
                InsertNote("导入A侧配置文件", listBox1);
                //cb_storage1.Enabled = false;
            }
            else
            {
                InsertNote("导入B侧配置文件", listBox1);
                //cb_storage6.Enabled = false;
            }

            try
            {

                checkBox_X13.Checked = (OperateIniFile.ReadIniData("Device", "tb_X13Box", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
                checkBox_X176.Checked = (OperateIniFile.ReadIniData("Device", "tb_X176Box", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
                checkBox_X177.Checked = (OperateIniFile.ReadIniData("Device", "tb_X177Box", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
                checkBox_X178.Checked = (OperateIniFile.ReadIniData("Device", "tb_X178Box", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
                checkBox_X19.Checked = (OperateIniFile.ReadIniData("Device", "tb_X19Box", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
                checkBox_Small.Checked = (OperateIniFile.ReadIniData("Device", "tb_SmallBox", "", Application.StartupPath + @"\Tool\Device.ini") == "1");
            }
            catch
            {
            }
        }

        #region Manual

        private void btn_plcread_Click(object sender, EventArgs e)
        {
            if (cb_plc.SelectedIndex==0)
            {
                short ret;
                plc1.ReadDeviceRandom2(tb_num.Text, 1, out ret);
                tb_plcread.Text = ret.ToString();
            }
            else if (cb_plc.SelectedIndex == 1)
            {
                short ret;
                plc2.ReadDeviceRandom2(tb_num.Text, 1, out ret);
                tb_plcread.Text = ret.ToString();
            }
            else if (cb_plc.SelectedIndex == 2)
            {
                short ret;
                plc3.ReadDeviceRandom2(tb_num.Text, 1, out ret);
                tb_plcread.Text = ret.ToString();
            }

        }

        private void btn_plcwrite_Click(object sender, EventArgs e)
        {
            if (cb_plc.SelectedIndex==0)
            {
                short ret = (short)Convert.ToInt16(tb_plcwrite.Text);
                plc1.WriteDeviceRandom2(tb_num.Text, 1, ref ret);
            }
            else if (cb_plc.SelectedIndex == 1)
            {
                short ret = (short)Convert.ToInt16(tb_plcwrite.Text);
                plc2.WriteDeviceRandom2(tb_num.Text, 1, ref ret);
            }
            else if (cb_plc.SelectedIndex == 2)
            {
                short ret = (short)Convert.ToInt16(tb_plcwrite.Text);
                plc3.WriteDeviceRandom2(tb_num.Text, 1, ref ret);
            }


        }

        private void btn_cam1shot_Click(object sender, EventArgs e)
        {
            try
            {
                HOperatorSet.GenEmptyObj(out m_image1);
                m_image1.Dispose();
                Camera1.GrabOnePic(out m_image1);
                HOperatorSet.DispObj(m_image1, hv_win1);
            }
            catch 
            {

            }

         }

        private void btn_scanner1_Click(object sender, EventArgs e)
        {
            KeyenceScanningGunModel_1.ScanCodeTimeout(SG1TimeOut);
        }

        private void btn_scanner2_Click(object sender, EventArgs e)
        {
            KeyenceScanningGunModel_2.ScanCodeTimeout(SG2TimeOut);
        }

        private void btn_scanner3_Click(object sender, EventArgs e)
        {
            KeyenceScanningGunModel_3.ScanCodeTimeout(SG3TimeOut);

        }

        private void btn_scanner4_Click(object sender, EventArgs e)
        {
            KeyenceScanningGunModel_4.ScanCodeTimeout(SG4TimeOut);
        }

        private void btn_test_Click(object sender, EventArgs e)
        {

            //string[]sss = result_detection.ToArray();
            //string a = string.Join(",", sss);
            //result_detection = result_detection.Skip(1).ToList();
            //double a = Convert.ToDouble("+00000.8");
            //T1 = new Thread(new ThreadStart(t1));
            //T2 = new Thread(new ThreadStart(t2));
            //T1.Start();
            //T2.Start();
            //sfcs("test");

            //string[] ret = new string[21];
            //MySqlFunction.Check_PacketData.Packet_Data_Check("'"+"FPW92654FWTMRK7AJ"+"'", ref ret);
            bool str = false;
            //string ret= Tray_Detection(m_image1, 1633.33, 2043.34, 0.00775275,1572.72, 1249.77,177,1000,ref str);
            //Tray_Detection(m_image1, row, col, phi, lenth1, lenth2, threshold, minarea, ref isCaer);
            Detection();
        }

        private void btn_clearresult_Click(object sender, EventArgs e)
        {
            if (cb_clearresult.SelectedIndex==0)
            {
                result_detection.Clear();
            }
            else if(cb_clearresult.SelectedIndex==1)
            {
                result_code.Clear();
            }
            else if (cb_clearresult.SelectedIndex==2)
            {
                result_type.Clear();
            }
            else if (cb_clearresult.SelectedIndex==3)
            {
                result_weight.Clear();
            }
            else if (cb_clearresult.SelectedIndex==4)
            {
                result_type_out.Clear();
            }
            else if (cb_clearresult.SelectedIndex==5)
            {
                result_detection.Clear();
                result_code.Clear();
                result_type.Clear();
                result_weight.Clear();
                result_type_out.Clear();

            }
        }

        private void btn_cam2shot_Click(object sender, EventArgs e)
        {
            HOperatorSet.GenEmptyObj(out m_image2);
            m_image2.Dispose();
            Camera1.GrabOnePic(out m_image2);
            HOperatorSet.DispObj(m_image2, hWindowControl2.HalconWindow);
        }

        private void btn_drawregion_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab (0);
            Thread.Sleep(10);
            HTuple hv_row = null, hv_col = null, hv_phi = null, hv_lenth1 = null, hv_lenth2 = null;
            try
            {
                HOperatorSet.DrawRectangle2(hv_win1, out hv_row, out hv_col, out hv_phi, out hv_lenth1, out hv_lenth2);
                OperateIniFile.WriteIniData("Device", "row", hv_row.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("Device", "col", hv_col.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("Device", "phi", hv_phi.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("Device", "lenth1", hv_lenth1.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("Device", "lenth2", hv_lenth2.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                row = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "row", "", Application.StartupPath + @"\Tool\Device.ini"));
                col = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "col", "", Application.StartupPath + @"\Tool\Device.ini"));
                phi = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "phi", "", Application.StartupPath + @"\Tool\Device.ini"));
                lenth1 = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "lenth1", "", Application.StartupPath + @"\Tool\Device.ini"));
                lenth2 = Convert.ToDouble(OperateIniFile.ReadIniData("Device", "lenth2", "", Application.StartupPath + @"\Tool\Device.ini"));
                InsertNote("修改区域成功", listBox1);
            }
            catch
            {
                InsertNote("修改区域失败", listBox1);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(10);
            HTuple hv_row1 = null, hv_col1 = null, hv_row2 = null, hv_col2 = null;
            try
            {
                HOperatorSet.DrawRectangle1(hv_win1, out hv_row1, out hv_col1, out hv_row2, out hv_col2);
                OperateIniFile.WriteIniData("DeviceCard1", "row1", hv_row1.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard1", "col1", hv_col1.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard1", "row2", hv_row2.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard1", "col2", hv_col2.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                row1Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "row1", "", Application.StartupPath + @"\Tool\Device.ini"));
                col1Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "col1", "", Application.StartupPath + @"\Tool\Device.ini"));
                row2Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "row2", "", Application.StartupPath + @"\Tool\Device.ini"));
                col2Card1 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard1", "col2", "", Application.StartupPath + @"\Tool\Device.ini"));

                InsertNote("修改区域成功", listBox1);
            }
            catch
            {
                InsertNote("修改区域失败", listBox1);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread.Sleep(10);
            HTuple hv_row1 = null, hv_col1 = null, hv_row2 = null, hv_col2 = null;
            try
            {
                HOperatorSet.DrawRectangle1(hv_win1, out hv_row1, out hv_col1, out hv_row2, out hv_col2);
                OperateIniFile.WriteIniData("DeviceCard2", "row1", hv_row1.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard2", "col1", hv_col1.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard2", "row2", hv_row2.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                OperateIniFile.WriteIniData("DeviceCard2", "col2", hv_col2.ToString(), Application.StartupPath + @"\Tool\Device.ini");
                row1Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "row1", "", Application.StartupPath + @"\Tool\Device.ini"));
                col1Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "col1", "", Application.StartupPath + @"\Tool\Device.ini"));
                row2Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "row2", "", Application.StartupPath + @"\Tool\Device.ini"));
                col2Card2 = Convert.ToDouble(OperateIniFile.ReadIniData("DeviceCard2", "col2", "", Application.StartupPath + @"\Tool\Device.ini"));

                InsertNote("修改区域成功", listBox1);
            }
            catch
            {
                InsertNote("修改区域失败", listBox1);
            }
        }

        private void btn_clearproductnum_Click(object sender, EventArgs e)
        {
            Product_Num[0] = 0;
            Product_Num[1] = 0;
            Product_Num[2] = 0;
            Product_Num[3] = 0;
            Product_Num[4] = 0;
            Product_Num[5] = 0;
            Product_Num[6] = 0;
            Product_Num[7] = 0;
            Product_Num[8] = 0;
            Product_Num[9] = 0;
            Product_Num[10] = 0;
            Product_Num[11] = 0;
        }

        private void checkBox_X13_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_X176_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_X177_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_X178_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_X19_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_Small_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void MoBasicVectorDisplay()
        {
            foreach (var item in Mo)
            {
                MoBasicVectorTextBox.Text += (item + "\r\n");
            }
        }

        private void MoBasicVectorTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            GetMoBasicVectorInTextBox(sender, ref Mo);
            UpdateMoBasicVector(Mo);
        }

        public void GetMoBasicVectorInTextBox(object sender, ref List<string> Mo)
        {
            Mo.Clear();
            string[] data = (sender as TextBox).Lines;
            foreach (string item in data)
            {
                string[] str = Regex.Split(item, "\\s+", RegexOptions.IgnoreCase);
                foreach (string item_ in str)
                {
                    if (item_ != "" && item_ != null)
                    {
                        Mo.Add(item_);
                    }
                }
            }
            ListDeWeight(Mo, ref Mo);
        }

        /// <summary>
        /// 移除重复元素
        /// </summary>
        /// <param name="inp"></param>
        /// <param name="outp"></param>
        private void ListDeWeight(List<string> inp, ref List<string> outp)
        {
            HashSet<string> data = new HashSet<string>(inp);
            outp.Clear();
            foreach (var item in data)
            {
                outp.Add(item);
            }
        }

        #region 分类Mo标记
        public static void MoBasicVectorLoad()
        {
            try
            {
                string[] MoBasicVector = XmlOperater.ReadItemFromXml(parameterFeilName, "IPC", "MoBasicVector", "Mo").Split(new char[] { '|' });

                foreach (var item in MoBasicVector)
                {
                    if (item != "" && item != null) Mo.Add(item);
                }

            }
            catch (Exception)
            {
            }
        }
        public static void UpdateMoBasicVector(List<string> Mo)
        {
            string Sets = "";
            foreach (var item in Mo)
            {
                Sets += item + "|";
            }
            XmlOperater.WriteItemToXml(parameterFeilName, "IPC", "MoBasicVector", "Mo", Sets);
        }
        #endregion
        #endregion

        //扫码枪
        //扫码返回值方法：正常返回SN/超时返回Timeouts
        private void QRcodeCallback1(ref string sn)
        {
            lab_Scanner1Code.Text = sn;
            str_scanner1code = sn.Replace("\r\n","");
        }
        private void QRcodeCallback2(ref string sn)
        {
            lab_Scanner2Code.Text = sn;
            str_scanner2code = sn.Replace("\r\n", "");
        }

        private void QRcodeCallback3(ref string sn)
        {
            lab_Scanner3Code.Text = sn;
            str_scanner3code = sn.Replace("\r\n", "");
        }
        private void QRcodeCallback4(ref string sn)
        {
            lab_Scanner4Code.Text = sn;
            str_scanner4code = sn.Replace("\r\n", "");
        }
        private void QRcodeCallback5(ref string sn)
        {
            str_scanner5code = sn.Replace("\r\n", "");
        }
        private void QRcodeCallback6(ref string sn)
        {
            str_scanner6code = sn.Replace("\r\n", "");
        }

        //扫码
        //private void Button1_Click(object sender, EventArgs e)
        //{
        //    KeyenceScanningGunModel_1.ScanCodeTimeout(7000);    //超时时间7s
        //    //KeyenceScanningGunModel_1.ScanCode();         //无超时
        //}

        public object lock1 = new object();
        public void InsertNote(string note,ListBox LB)     //日志
        {
            lock(lock1)
            {
                if (note != last_note)
                {
                    string time = DateTime.Now.ToString();
                    LB.Items.Insert(0, time + ": " + note);
                    last_note = note;
                    SaveLog(note);
                }
            }

        }

        private void SaveLog(string msg)     //保存log
        {
            string logname = DateTime.Now.ToString("yyyy-MM-dd");
            txthelper.WriteText(Application.StartupPath + "\\Log\\" + logname + ".log", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + msg);

        }

        public object lock2 = new object();
        public void InsertNote1(string note, ListBox LB)     //分板来料异常日志
        {
            lock (lock2)
            {
                if (note != last_note1)
                {
                    string time = DateTime.Now.ToString();
                    LB.Items.Insert(0, time + ": " + note);
                    last_note1 = note;
                    SaveLog1(note);
                }
            }

        }

        private void SaveLog1(string msg)     //保存log
        {
            string logname = DateTime.Now.ToString("yyyy-MM-dd");
            txthelper2.WriteText(Application.StartupPath + "\\Log\\" + logname + "error.log", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + msg);

        }


        private void SaveImage(string type, HObject m_image)   //保存照片
        {
            HOperatorSet.WriteImage(m_image, "tiff", 0, Application.StartupPath + "\\SaveImage\\" + type +"-"+DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.fff")  + ".tiff"); 

        }
/// <summary>
/// 
/// </summary>
        private void Entrance_Scan()   //入口处扫码
        {
            str_scanner1code = "ERROR";
            Thread.Sleep(1000);
            KeyenceScanningGunModel_1.ScanCodeTimeout(SG1TimeOut);
            Thread.Sleep(1200);

            if(str_scanner1code.Length<17)
            {
                InsertNote("入口处扫码 ERROR", listBox2);
            }

            MySqlFunction.PacketData_P.Packet_Data_Delete_P("'" + str_scanner1code + "'");
            WZS_SFCS.clsInfoNameValue[] sfcs_ret = { };
            short type=0;
            try
            {

                Mes.GetKeyInfoFromView(str_scanner1code, "PO", "15", ref sfcs_ret);
                InsertNote("入口处扫码SFCS反馈结果：" + str_scanner1code + ":" + sfcs_ret[0].InfoValue.ToString(), listBox1);
                type = Check_tray_type(sfcs_ret[0].InfoValue.ToString().Split('|')[3]);
            }
            catch
            {
                InsertNote("入口处扫码SFCS ERROR", listBox1);
            }

            string[] mysql_ret = new string[21];
            MySqlFunction.Check_PacketData.Packet_Data_Check("'" + str_scanner1code + "'", ref mysql_ret);

            //入口处扫码后反馈盖空盘种类
            short ret3 = type;
            plc1.WriteDeviceRandom2(Out7, 1, ref ret3);
            InsertNote(Out7+"——给分类信息:" + ret3.ToString(), listBox1);

            short ret2;
            if (mysql_ret[20] != null)
            {
                if (Convert.ToInt16(mysql_ret[20])==20)
                {
                    if (cb_mode.SelectedIndex==0)
                    {
                        ret2 = 2;
                        InsertNote("自动段满箱来料,目前强制分盘", listBox1);
                    }
                    else
                    {
                        ret2 = 1;
                        InsertNote("自动段满箱来料,不分板", listBox1);
                        MySqlFunction.PacketData_P.PacketData_INSERT_P(mysql_ret.Take(20).ToList());
                    }

                }
                else if (Convert.ToInt16(mysql_ret[20]) != 20 && cb_packagemode.SelectedIndex==0)
                {
                    ret2 = 3;
                    InsertNote("自动段未满箱来料，且不包装", listBox1);
                }
                else
                {
                    ret2 = 2;
                    InsertNote("自动段未满箱来料，且要包装", listBox1);
                }

            }
            else if (str_scanner1code == "ERROR"|| str_scanner1code=="Timeouts"||type==0)
            {
                ret2 = 3;
                InsertNote("入口处扫码NG", listBox1);
            }
            else
            {
                ret2 = 2;
                InsertNote("人工段来料", listBox1);
            }

            plc1.WriteDeviceRandom2(Out0, 1, ref ret2);
            InsertNote(Out0+"——反馈扫码完成", listBox1);
            T_Entrance_Scan.Abort();
        }

        private void Detection()     //异物检测
        {
            isCaer = false;
            try
            {
                HOperatorSet.GenEmptyObj(out m_image1);
                m_image1.Dispose();
                Camera1.GrabOnePic(out m_image1);
                HOperatorSet.DispObj(m_image1, hv_win1);
                string detection_result = Tray_Detection(m_image1, row, col, phi, lenth1, lenth2, threshold, minarea);
                m_image1.Dispose();
                result_detection.Add(detection_result);
            }
            catch
            {

            }

            short ret2 = 1;
            plc1.WriteDeviceRandom2(Out1, 1, ref ret2);
            InsertNote(Out1+"——反馈异物检测完成", listBox1);
            T_Detection.Abort();
        }

        private void Seperate_Scan()  //分板扫码
        {
            str_scanner2code = "ERROR";
            str_scanner3code = "ERROR";
            Thread.Sleep(200);
            KeyenceScanningGunModel_2.ScanCodeTimeout(SG2TimeOut);
            KeyenceScanningGunModel_3.ScanCodeTimeout(SG3TimeOut);
            Thread.Sleep(1200);

            if (str_scanner2code.Length < 17)
            {
                InsertNote("分板处A扫码 ERROR", listBox2);
            }
            if (str_scanner3code.Length < 17 )
            {
                InsertNote("分板处B扫码 ERROR", listBox2);
            }

            result_code.Add(str_scanner2code);
            result_code.Add(str_scanner3code);
            WZS_SFCS.clsInfoNameValue[] sfcs_ret1 = { };
            WZS_SFCS.clsInfoNameValue[] sfcs_ret2 = { };
            try
            {
                Mes.GetKeyInfoFromView(str_scanner2code, "PO", "15", ref sfcs_ret1);
                InsertNote("分板扫码1 SFCS反馈结果："+str_scanner2code+":"+sfcs_ret1[0].InfoValue.ToString(), listBox1);
                result_type.Add(sfcs_ret1[0].InfoValue.ToString().Split('|')[0]+"|"+
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[3] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[4] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[6] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[7] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[10] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[11] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[12] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[13] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[18] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[14] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[15] +"|"+
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[16] + "|" +
                                sfcs_ret1[0].InfoValue.ToString().Split('|')[1]);
                MySqlFunction.PacketData_P.Packet_Data_Delete_P("'"+str_scanner2code+"'");
            }
            catch
            {
                InsertNote("分板扫码1 SFCS ERROR", listBox1);
                result_type.Add("0|0|0|0|0|0|0|0|0|0|0|0|0|0");
            }

            try
            {
                Mes.GetKeyInfoFromView(str_scanner3code, "PO", "15", ref sfcs_ret2);
                InsertNote("分板扫码2 SFCS反馈结果：" +str_scanner3code+":"+ sfcs_ret2[0].InfoValue.ToString(), listBox1);
                result_type.Add(sfcs_ret2[0].InfoValue.ToString().Split('|')[0] + "|" +                             
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[3] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[4] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[6] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[7] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[10] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[11] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[12] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[13] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[18] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[14] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[15] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[16] + "|" +
                                sfcs_ret2[0].InfoValue.ToString().Split('|')[1]);
                MySqlFunction.PacketData_P.Packet_Data_Delete_P("'"+str_scanner3code+"'");
            }
            catch
            {
                InsertNote("分板扫码2 SFCS ERROR", listBox1);
                result_type.Add("0|0|0|0|0|0|0|0|0|0|0|0|0|0");
            }


            short ret2 = 1;
            plc1.WriteDeviceRandom2(Out2, 1, ref ret2);
            InsertNote(Out2+"——反馈人工段来料分板扫码完成", listBox1);
            T_Seperate_Scan.Abort();
        }

        private void Front_Weighing( object D )  //前端称重
        {
            Thread.Sleep(1700);

            while (true)
            {
                Thread.Sleep(10);
                try
                {
                    str_weight1 = Scales1.ReceiveData.Split(' ')[0];
                    double weight_mid = Convert.ToDouble(str_weight1);
                    if (weight_mid>0)
                    {
                        break;
                    }
                }
                catch
                {

                }
            }

            lab_Weight1.Text = str_weight1;
            result_weight.Add(str_weight1);

            if ((short)D == 100)
            {
                short ret;
                plc1.ReadDeviceRandom2(In7, 1, out ret);
                InsertNote(In7+"——有产品的盘数==" + ret.ToString(), listBox1);

                int count = result_weight.Count;
                InsertNote(In4+"=100,放空盘完成,总盘数：" + count.ToString(), listBox1);
                if (count<ret)
                {
                    InsertNote("计数错误！！！",listBox1);
                    Auto_Thread.Abort();
                    MessageBox.Show("PLC计数错误！请重启软件，复位清料再启动！！！");
                }
                InsertNote("异物检测结果："+ string.Join(",", result_detection.Take(ret).ToList().ToArray()), listBox1);
                InsertNote("条码：" + string.Join(",", result_code.Take(2 * ret).ToList().ToArray()), listBox1);
                InsertNote("条码类型：" + string.Join(",", result_type.Take(2 * ret).ToList().ToArray()), listBox1);
                InsertNote("重量：" + string.Join(",", result_weight.ToArray()), listBox1);

                if (Check_Seperate_Result_New(result_detection.Take(ret).ToList(), result_code.Take(2 * ret).ToList(), result_type.Take(2 * ret).ToList(),result_weight.Take(ret).ToList()))
                {
                    List<string> Insert_Usn = new List<string>();
                    Insert_Usn = result_code.Take(2 * ret).ToList();
                    if (Insert_Usn.Count < 20)
                    {
                        int con = 20 - Insert_Usn.Count;
                        for (int i = 0; i < con; i++)
                        {
                            Insert_Usn.Add("");
                        }
                    }
                    MySqlFunction.PacketData_P.PacketData_INSERT_P(Insert_Usn);
                    InsertNote("物料匹对通过，写入本地数据库", listBox1);
                }

                result_detection = result_detection.Skip(ret).ToList();
                result_code = result_code.Skip(2 * ret).ToList();
                result_type = result_type.Skip(2 * ret).ToList();
                result_weight.Clear();

            }

            short ret2 = 1;
            plc1.WriteDeviceRandom2(Out4, 1, ref ret2);
            InsertNote(Out4+"——反馈手动段来料分板称重完成", listBox1);

            T_Front_Weighing.Abort();
        }

        private void Exprot_Scan()    //出口处扫码
        {
            str_scanner4code = "ERROR";
            Thread.Sleep(300);
            KeyenceScanningGunModel_4.ScanCodeTimeout(SG4TimeOut);
            Thread.Sleep(1200);

            if (str_scanner4code.Length < 17)
            {
                InsertNote("出口处扫码 ERROR", listBox2);
            }

            string[] mysql_ret = new string[21];
            MySqlFunction.PacketData_P.Packet_Data_Check_P("'" + str_scanner4code + "'", ref mysql_ret);

            WZS_SFCS.clsInfoNameValue[] sfcs_ret = { };
            try
            {
                Mes.GetKeyInfoFromView(str_scanner4code, "PO", "15", ref sfcs_ret);               
                InsertNote("出口处扫码SFCS反馈结果：" + str_scanner4code + ":" + sfcs_ret[0].InfoValue.ToString(), listBox1);
            }
            catch
            {
                InsertNote("出口处扫码SFCS ERROR", listBox2);
                InsertNote("出口处扫码SFCS ERROR", listBox1);
            }

            short ret2;
            if (mysql_ret[20]!=null&& sfcs_ret.Length!=0)
            {
                if (Convert.ToInt16(mysql_ret[20])!=20&&cb_packagemode.SelectedIndex==0)
                {
                    ret2 = 2;
                    InsertNote("异常物料", listBox1);
                }
                else
                {
                    ret2 = 1;
                    //result_type_out.Add(sfcs_ret[0].InfoValue.ToString().Split('|')[3] + "," + string.Join(",", mysql_ret.ToArray()));
                    MySqlFunction.Check_Label.Label_INSERT(mysql_ret.Take(20).ToList());
                    InsertNote("正常物料", listBox1);
                }

               
            }
            else
            {
                ret2 = 2;
                InsertNote("异常物料", listBox1);
            }


            plc1.WriteDeviceRandom2(Out5, 1, ref ret2);
            InsertNote(Out5+"——反馈异常排料前扫码完成并给出排料结果", listBox1);

            T_Export_Scan.Abort();
        }

        private void Final_Weighing()   //最后称重
        {
            InsertNote("B001", listBox1);
            str_scanner6code = "ERROR";
            Thread.Sleep(200);
            KeyenceScanningGunModel_6.ScanCodeTimeout(SG6TimeOut);
            Thread.Sleep(1000);
            InsertNote("B002", listBox1);
            if (str_scanner6code.Length < 17)
            {
                InsertNote("称重处扫码 ERROR", listBox2);
            }
            else
            {
                InsertNote("称重处扫码 " + str_scanner6code.ToString(), listBox2);
            }
            

            InsertNote("B003", listBox1);
            string[] mysql_ret = new string[21];
            MySqlFunction.PacketData_P.Packet_Data_Check_P("'" + str_scanner6code + "'", ref mysql_ret);
            InsertNote("B004", listBox1);
            WZS_SFCS.clsInfoNameValue[] sfcs_ret = { };
            try
            {
                InsertNote("B005", listBox1);
                Action action = () =>
                {
                    InsertNote("A001", listBox1);
                    Mes.GetKeyInfoFromView(str_scanner6code, "PO", "15", ref sfcs_ret);
                    InsertNote("A002", listBox1);
                };
                Task.Run(action);
                InsertNote("B006", listBox1);
                Thread.Sleep(1000); //等待时间
                if (sfcs_ret.Length == 0)
                {
                    InsertNote("超时访问", listBox1);
                }
                else
                {
                    InsertNote("有效访问", listBox1);
                }
                
                InsertNote("称重处扫码SFCS反馈结果：" +str_scanner6code+":"+ sfcs_ret[0].InfoValue.ToString(), listBox1);
            }
            catch
            {
                InsertNote("称重处扫码SFCS ERROR", listBox2);
                InsertNote("称重处扫码SFCS ERROR", listBox1);
            }

            while (true)
            {
                InsertNote("B007", listBox1);
                Thread.Sleep(10);
                try
                {
                    str_weight2 = Scales2.ReceiveData.Split(' ')[0];
                    double weight_mid = Convert.ToDouble(str_weight2);
                    if (weight_mid>0)
                    {
                        InsertNote("B008", listBox1);
                        break;
                    }
                }
                catch
                {

                }
            }


            lab_Weight2.Text = str_weight2;
            double weight_now = Convert.ToDouble(str_weight2);
            double weight_last = 0;
            while (true)
            {
                InsertNote("B009", listBox1);
                Thread.Sleep(50);

                try
                {
                    weight_last = Convert.ToDouble(Scales2.ReceiveData.Split(' ')[0]);

                }
                catch 
                {

                }
                if ((weight_last-weight_now)>42&& (weight_last - weight_now) < 58)
                {
                    InsertNote("B010", listBox1);
                    break;
                }
            }
            if (mysql_ret[20]!=null && sfcs_ret.Length != 0)
            {
                if ((weight_now < Check_type_Totalweight(sfcs_ret[0].InfoValue.ToString().Split('|')[3])[0] || weight_now > Check_type_Totalweight(sfcs_ret[0].InfoValue.ToString().Split('|')[3])[1])&&
                    Convert.ToInt16(mysql_ret[20]) == 20)
                {
                    InsertNote("十盘+空tray重量未达标！按确认后物料会弹出，此物料请勿打包！！！", listBox1);
                    MessageBox.Show("十盘+空tray重量未达标！按确认后物料会弹出，此物料请勿打包！！！");
                    short ret2 = 1;
                    plc1.WriteDeviceRandom2(Out6, 1, ref ret2);
                    InsertNote(Out6 + "——十盘+空tray重量未达标后弹出物料", listBox1);
                    Mark_Weight = "Ready";
                    Mark_BoxConfirm = "Ready";
                    MySqlFunction.PacketData_P.Packet_Data_Delete_P("'" + str_scanner6code + "'");
                    T_Final_Weighing.Abort();
                }
                else
                {

                    lab_BoxType.Text = sfcs_ret[0].InfoValue.ToString().Split('|')[3];

                    short ret2 = 1;
                    plc1.WriteDeviceRandom2(Out6, 1, ref ret2);
                    InsertNote(Out6 + "——反馈异常排料后称总重完成，重量：" + weight_last.ToString(), listBox1);

                    short greenlight = 1;
                    short redlight = 0;
                    plc3.WriteDeviceRandom2(POut2, 1, ref greenlight);
                    plc3.WriteDeviceRandom2(POut3, 1, ref redlight);

                    short ret3;
                    plc3.ReadDeviceRandom2(POut1, 1, out ret3);

                    if (ret3 == 0)
                    {
                        string type = sfcs_ret[0].InfoValue.ToString().Split('|')[3];
                        Out_Type = type;
                        if (tb_typeX01.Text.Contains(type) || tb_typeX03.Text.Contains(type) || tb_typeX05.Text.Contains(type) || tb_typeX08.Text.Contains(type) || tb_typeX15.Text.Contains(type))
                        {
                            short ret4 = 11;
                            if (!checkBox_Small.Checked)
                            {
                                plc3.WriteDeviceRandom2(POut1, 1, ref ret4);
                                InsertNote(type + ":出小箱子", listBox1);
                            }

                        }
                        else
                        {
                            short ret4 = 22;

                            if ((tb_typeX13.Text.Contains(type) && !checkBox_X13.Checked) ||
                                (tb_typeX176.Text.Contains(type) && !checkBox_X176.Checked) ||
                                (tb_typeX177.Text.Contains(type) && !checkBox_X177.Checked) ||
                                (tb_typeX178.Text.Contains(type) && !checkBox_X178.Checked) ||
                                (tb_typeX19.Text.Contains(type) && !checkBox_X19.Checked) )
                            {
                                plc3.WriteDeviceRandom2(POut1, 1, ref ret4);
                                InsertNote(type + ":出大箱子", listBox1);
                            }
                        }

                    }
                    else
                    {
                        InsertNote(POut1 + "!=0，该位置还有箱子", listBox1);
                    }

                    string ret_print = Mes.AutoPackingforFATP(string.Join(",", mysql_ret.Take(Convert.ToInt16(mysql_ret[20]))), "PO", StationPO, "TB1-1FT-PO", FATP_UserID);
                    InsertNote("FATP 结果：" + ret_print + " SN数量：" + mysql_ret[20] + " 分别是：" + string.Join(",", mysql_ret.Take(Convert.ToInt16(mysql_ret[20]))), listBox1);
                    Thread.Sleep(500);
                    string ret_weight = Mes.AutoWeight(mysql_ret[0], weight_last.ToString(), "PP", StationPP, "TB1-1FT-PO", Weight_UserID);
                    InsertNote("请求打印：" + ret_weight, listBox1);

                    Product_Num[0]++;

                    if (ret_print == "OK" && ret_weight != "OK")
                    {
                        Thread.Sleep(1500);
                        string ret_weight2 = Mes.AutoWeight(mysql_ret[0], weight_last.ToString(), "PP", StationPP, "TB1-1FT-PO", Weight_UserID);
                        InsertNote("carton id生成OK,打印失败，再次请求打印：" + ret_weight2, listBox1);
                    }

                    Scanner_Box_Confirm.ReceiveData = "";
                    Mark_BoxConfirm = "Operating";
                    MySqlFunction.PacketData_P.Packet_Data_Delete_P("'" + str_scanner6code + "'");
                    T_Final_Weighing.Abort();
                }
            }
            else
            {
                InsertNote("扫码NG导致捞数据失败！按确认后物料会弹出，此物料请勿打包！！！", listBox1);
                MessageBox.Show("扫码NG导致捞数据失败！按确认后物料会弹出，此物料请勿打包！！！");
                short ret2 = 1;
                plc1.WriteDeviceRandom2(Out6, 1, ref ret2);
                InsertNote(Out6 + "——称重扫码NG弹出物料",listBox1);
                Mark_Weight = "Ready";
                Mark_BoxConfirm = "Ready";
                T_Final_Weighing.Abort();
            }

        }

        private void Check_Box_Label()
        {
            str_scanner5code = "ERROR";
            KeyenceScanningGunModel_5.ScanCodeTimeout(SG5TimeOut);
            Thread.Sleep(1600);

            if (str_scanner5code.Length < 17)
            {
                //InsertNote("Box_Label ERROR", listBox2);
            }

            string[] mysql_ret = new string[21];
            MySqlFunction.Check_Label.Label_Check("'" + str_scanner5code + "'", ref mysql_ret);
            short ret;
            if (str_scanner5code=="ERROR"||str_scanner5code=="Timeouts"|| mysql_ret[20] == null)
            {
                ret = 2;
            }
            else
            {
                ret = 1;
            }
            MySqlFunction.Check_Label.Label_Delete("'" + str_scanner5code + "'");
            plc3.WriteDeviceRandom2(POut4, 1, ref ret);

            T_Check_Box_Label.Abort();
        }

        private bool Check_Seperate_Result(List<string>detection,List<string>code,List<string>type,List<string>weight)  //分板完成后对比条码是否ng，异物检测是否ng，类型是否匹对，重量是否合格
        {
            if (detection.Contains("NG"))
            {
                InsertNote("异物检测未通过", listBox1);
                return false;
            }
            else if (code.Contains("ERROR") || code.Contains("Timeouts"))
            {
                InsertNote("有NG条码未通过", listBox1);
                return false;
            }
            else
            {
                int Route_Error_Num = 0;
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[3]!="PO")
                    {
                        Route_Error_Num++;
                    }
                }
                if (Route_Error_Num!=0)
                {
                    InsertNote("有物料站别错误", listBox1);
                    return false;
                }

                int Hold_Num = 0;
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[4] != "NO")
                    {
                        Hold_Num++;
                    }
                }
                if (Hold_Num!=0)
                {
                    InsertNote("有物料被HOLD", listBox1);
                    return false;
                }

                int Type_Error_Num = 0;
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i]!=type[0])
                    {
                        Type_Error_Num++;
                    }       
                }
                if (Type_Error_Num==0)
                {
                    int Weight_Error_Num = 0;
                    for (int i = 1; i < weight.Count; i++)
                    {
                        if ((Convert.ToDouble(weight[i])-Convert.ToDouble(weight[i-1])-Check_type_weight(type[0].Split('|')[1])[0])<0 || (Convert.ToDouble(weight[i]) - Convert.ToDouble(weight[i - 1]) - Check_type_weight(type[0].Split('|')[1])[1]) > 0)
                        {
                            Weight_Error_Num++;
                        }
                    }
                    if (Weight_Error_Num==0)
                    {
                        return true;
                    }
                    else
                    {
                        InsertNote("称重未通过", listBox1);
                        return false;
                    }
                }
                else
                {
                    InsertNote("物料类型匹对未通过", listBox1);
                    return false;
                }
            }
        }

        private bool Check_Seperate_Result_New(List<string> detection, List<string> code, List<string> type, List<string> weight)
        {
            string Total_Msg = "";
            List<string> Info = new List<string>();
            Info.Add("有异物");
            Info.Add("条码NG");
            Info.Add("站别错误");
            Info.Add("被Hold");
            Info.Add("混料");
            Info.Add("重量异常");
            Info.Add("没CheckOut");
            Info.Add("库类错误");
            Info.Add("WMS");
            Info.Add("CQABLNG");
            Info.Add("X17_Tilt");
            List<string> Msg = new List<string>();
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            Msg.Add("");
            int Detection_NG_Num = 0;
            int Code_ERROR_Num = 0;
            int Route_ERROR_Num = 0;
            int Hold_Num = 0;
            int Type_ERROR_Num = 0;
            int Weight_ERROR_Num = 0;
            int Check_ERROR_Num = 0;
            int Lib_ERROR_Num = 0;
            int WMS_ERROR_Num = 0;
            int CQA_ERROR_Num = 0;
            int X17_Tilt_NG_Num = 0;
            for (int i = 0; i < detection.Count; i++)
            {
                if (detection[i]=="NG")
                {
                    Msg[0] = Msg[0] + (detection.Count - i).ToString()+",";
                    Detection_NG_Num++;
                }
            }

            for (int i = 0; i < code.Count; i++)
            {
                if (code[i] == "ERROR"||code[i]=="Timeouts")
                {
                    int num;
                    if (((code.Count-i)%2)==0)
                    {
                        num = (code.Count - i) / 2;
                    }
                    else
                    {
                        num = (code.Count - i + 1) / 2;
                    }
                    Msg[1] = Msg[1] + num.ToString() + ",";
                    Code_ERROR_Num++;
                }
            }

            if (Code_ERROR_Num==0)
            {
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[3] != "PO")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[2] = Msg[2] + num.ToString() + ",";
                        Route_ERROR_Num++;
                    }
                }

                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[4] != "NO")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[3] = Msg[3] + num.ToString() + ",";
                        Hold_Num++;
                    }
                }

                for (int i = 0; i < type.Count; i++)
                {
                    //MO
                    bool fMo = false;
                    if (Mo.Contains(type[i].Split('|')[13]))
                    {
                        for (int j = 0; j < i; j++)
                        {
                            if (type[j].Split('|')[13] != type[i].Split('|')[13])
                            {
                                fMo = true;
                            }
                        }                        
                    }
                    if (type[i].Split('|')[0] != type[0].Split('|')[0] || type[i].Split('|')[1] != type[0].Split('|')[1] || type[i].Split('|')[2] != type[0].Split('|')[2] || type[i].Split('|')[5] != type[0].Split('|')[5] || 
                        type[i].Split('|')[10] != type[0].Split('|')[10] || type[i].Split('|')[11] != type[0].Split('|')[11] || type[i].Split('|')[12] != type[0].Split('|')[12]||
                        fMo)
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[4] = Msg[4] + num.ToString() + ",";
                        Type_ERROR_Num++;
                    }
                }

                for (int i = 0; i < weight.Count; i++)
                {
                    if (i == 0)
                    {
                        if ((Convert.ToDouble(weight[i]) - Check_type_weight(type[0].Split('|')[1])[0]) < 0 || (Convert.ToDouble(weight[i]) - Check_type_weight(type[0].Split('|')[1])[1]) > 0)
                        {
                            Msg[5] = Msg[5] + (weight.Count - i).ToString() + ",";
                            Weight_ERROR_Num++;
                        }
                    }
                    else
                    {
                        if ((Convert.ToDouble(weight[i]) - Convert.ToDouble(weight[i - 1]) - Check_type_weight(type[0].Split('|')[1])[0]) < 0 || (Convert.ToDouble(weight[i]) - Convert.ToDouble(weight[i - 1]) - Check_type_weight(type[0].Split('|')[1])[1]) > 0)
                        {
                            Msg[5] = Msg[5] + (weight.Count - i).ToString() + ",";
                            Weight_ERROR_Num++;
                        }
                    }

                }

                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[6] != "OUT")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[6] = Msg[6] + num.ToString() + ",";
                        Check_ERROR_Num++;
                    }
                }
               
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[7]!=type[0].Split('|')[7])
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[7] = Msg[7] + num.ToString() + ",";
                        Lib_ERROR_Num++;
                    }
                }

                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[8] == "WMS")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[8] = Msg[8] + num.ToString() + ",";
                        WMS_ERROR_Num++;
                    }
                }

                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[9] == "NG")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[9] = Msg[9] + num.ToString() + ",";
                        CQA_ERROR_Num++;
                    }
                }
                for (int i = 0; i < type.Count; i++)
                {
                    if (type[i].Split('|')[10] == "NG")
                    {
                        int num;
                        if (((type.Count - i) % 2) == 0)
                        {
                            num = (type.Count - i) / 2;
                        }
                        else
                        {
                            num = (type.Count - i + 1) / 2;
                        }
                        Msg[10] = Msg[10] + num.ToString() + ",";
                        X17_Tilt_NG_Num++;
                    }
                }

            }
            if (Detection_NG_Num!=0)
            {
                Product_Num[1]++;
            }
            if (Code_ERROR_Num != 0)
            {
                Product_Num[2]++;
            }
            if (Route_ERROR_Num != 0)
            {
                Product_Num[3]++;
            }
            if (Hold_Num != 0)
            {
                Product_Num[4]++;
            }
            if (Type_ERROR_Num != 0)
            {
                Product_Num[5]++;
            }
            if (Weight_ERROR_Num != 0)
            {
                Product_Num[6]++;
            }
            if (Check_ERROR_Num != 0)
            {
                Product_Num[7]++;
            }
            if (Lib_ERROR_Num!=0)
            {
                Product_Num[8]++;
            }
            if (WMS_ERROR_Num != 0)
            {
                Product_Num[9]++;
            }
            if (CQA_ERROR_Num != 0)
            {
                Product_Num[10]++;
            }
            if (X17_Tilt_NG_Num!=0)
            {
                Product_Num[11]++;
            }
            if (Detection_NG_Num == 0 && Code_ERROR_Num == 0 && Route_ERROR_Num == 0 && Hold_Num == 0 && Type_ERROR_Num == 0 && Weight_ERROR_Num == 0 && Check_ERROR_Num==0&&Lib_ERROR_Num==0&& WMS_ERROR_Num == 0&& CQA_ERROR_Num == 0&& X17_Tilt_NG_Num==0)
            {
                return true;
            }
            else
            {
                for (int i = 0; i < Msg.Count; i++)
                {
                    if (Msg[i]!="")
                    {
                        Total_Msg = Total_Msg + Msg[i] + Info[i] + " & ";
                    }
                }
                string result = "人工来料";
                try
                {
                    string[] mysql_ret = new string[21];
                    MySqlFunction.Check_PacketData.Packet_Data_Check("'" + code[0] + "'", ref mysql_ret);
                    if (mysql_ret[20]!=null)
                    {
                        result = "分板来料";
                        InsertNote1("异常情况:" +type[0].Split('|')[1] +"  "+ Total_Msg+result, listBox1);
                    }
                }
                catch
                {

                }

                InsertNote("异常情况:" + type[0].Split('|')[1] + "  " + Total_Msg+result, listBox2);
                InsertNote("异常情况:" + type[0].Split('|')[1] + "  " + Total_Msg+result, listBox1);
                return false;
            }



        }

        private short Check_tray_type(string type)   //传入类型 如X1029  返回空吹盘类型 X1=1,X3=2,X5=3,X8=4,X13=5,X15=6,X176=7,X177=8,X178=9,,X19=10,
        {
            if (tb_typeX01.Text.Contains(type))
            {
                return 1;
            }
            else if (tb_typeX03.Text.Contains(type))
            {
                return 2;

            }
            else if (tb_typeX05.Text.Contains(type))
            {
                return 3;

            }
            else if (tb_typeX08.Text.Contains(type))
            {
                return 4;

            }
            else if (tb_typeX13.Text.Contains(type))
            {
                return 5;

            }
            else if (tb_typeX15.Text.Contains(type))
            {
                return 6;

            }
            else if (tb_typeX176.Text.Contains(type))
            {
                return 7;

            }
            else if (tb_typeX177.Text.Contains(type))
            {
                return 8;

            }
            else if (tb_typeX178.Text.Contains(type))
            {
                return 9;

            }
            else if (tb_typeX19.Text.Contains(type))
            {
                return 10;

            }
            else
            {
                return 0;
            }

        }

        private double[] Check_type_weight(string type)   //传入类型 如X1029  返回该类型的一盘料的最小值和最大值重量
        {
            double[] weight = new double[2];
            if (tb_typeX01.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweight1min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweight1max.Text);
                }
                catch 
                {
                    weight[0] = 206;
                    weight[1] = 255;
                }

            }
            else if (tb_typeX03.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX3min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX3max.Text);
                }
                catch
                {
                    weight[0] = 206;
                    weight[1] = 255;
                }

            }
            else if (tb_typeX05.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX5min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX5max.Text);
                }
                catch
                {
                    weight[0] = 206;
                    weight[1] = 255;
                }

            }
            else if (tb_typeX08.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX8min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX8max.Text);
                }
                catch
                {
                    weight[0] = 206;
                    weight[1] = 255;
                }

            }
            else if (tb_typeX15.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX15min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX15max.Text);
                }
                catch
                {
                    weight[0] = 206;
                    weight[1] = 255;
                }

            }
            else if(tb_typeX13.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweight2min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweight2max.Text);
                }
                catch
                {
                    weight[0] = 245;
                    weight[1] = 285;
                }

            }
            else if (tb_typeX176.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX176min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX176max.Text);
                }
                catch
                {
                    weight[0] = 245;
                    weight[1] = 285;
                }

            }
            else if (tb_typeX177.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX177min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX177max.Text);
                }
                catch
                {
                    weight[0] = 245;
                    weight[1] = 285;
                }

            }
            else if (tb_typeX178.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX178min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX178max.Text);
                }
                catch
                {
                    weight[0] = 245;
                    weight[1] = 285;
                }

            }
            else if (tb_typeX19.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_singleweightX19min.Text);
                    weight[1] = Convert.ToDouble(tb_singleweightX19max.Text);
                }
                catch
                {
                    weight[0] = 245;
                    weight[1] = 285;
                }

            }
            return weight;
        }
        private double[] Check_type_Totalweight(string type)   //传入类型 如X1029  返回该类型的十盘料加空tray的最小值和最大值重量
        {
            double[] weight = new double[2];
            if (tb_typeX01.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X1min.Text);
                    weight[1] = Convert.ToDouble(tb_X1max.Text);
                }
                catch
                {
                    weight[0] = 2350;
                    weight[1] = 2540;
                }

            }
            else if (tb_typeX03.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X3min.Text);
                    weight[1] = Convert.ToDouble(tb_X3max.Text);
                }
                catch
                {
                    weight[0] = 2250;
                    weight[1] = 2380;
                }
            }
            else if (tb_typeX05.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X5min.Text);
                    weight[1] = Convert.ToDouble(tb_X5max.Text);
                }
                catch
                {
                    weight[0] = 2360;
                    weight[1] = 2480;
                }
            }
            else if (tb_typeX08.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X8min.Text);
                    weight[1] = Convert.ToDouble(tb_X8max.Text);
                }
                catch
                {
                    weight[0] = 2350;
                    weight[1] = 2540;
                }
            }
            else if (tb_typeX15.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X15min.Text);
                    weight[1] = Convert.ToDouble(tb_X15max.Text);
                }
                catch
                {
                    weight[0] = 2430;
                    weight[1] = 2490;
                }
            }
            else if(tb_typeX13.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X13min.Text);
                    weight[1] = Convert.ToDouble(tb_X13max.Text);
                }
                catch
                {
                    weight[0] = 2640;
                    weight[1] = 2760;
                }

            }
            else if (tb_typeX176.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X176min.Text);
                    weight[1] = Convert.ToDouble(tb_X176max.Text);
                }
                catch
                {
                    weight[0] = 2640;
                    weight[1] = 2760;
                }

            }
            else if (tb_typeX177.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X177min.Text);
                    weight[1] = Convert.ToDouble(tb_X177max.Text);
                }
                catch
                {
                    weight[0] = 2640;
                    weight[1] = 2760;
                }

            }
            else if (tb_typeX178.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X178min.Text);
                    weight[1] = Convert.ToDouble(tb_X178max.Text);
                }
                catch
                {
                    weight[0] = 2640;
                    weight[1] = 2760;
                }

            }
            else if (tb_typeX19.Text.Contains(type))
            {
                try
                {
                    weight[0] = Convert.ToDouble(tb_X19min.Text);
                    weight[1] = Convert.ToDouble(tb_X19max.Text);
                }
                catch
                {
                    weight[0] = 2640;
                    weight[1] = 2760;
                }

            }
            return weight;
        }

        private string Check_Box_Type(string type)
        {
            if (tb_typeX01.Text.Contains(type) || tb_typeX03.Text.Contains(type) || tb_typeX05.Text.Contains(type) || tb_typeX08.Text.Contains(type) || tb_typeX15.Text.Contains(type))
            {
                return "A0501";
            }
            else
            {
                return "0D801";
            }
        }

        private string Tray_Detection(HObject image, double row,double col,double phi,double lenth1,double lenth2,double threshold,double min_area)
        {
            try
            {

                bool b_model = Find_Model(image);

                // Local iconic variables 

                HObject ho_Rectangle = null, ho_Rectangle1 = null, ho_Rectangle2 = null, ho_ImageReduced = null;
                HObject ho_Regions = null, ho_RegionOpening = null, ho_ConnectedRegions = null;
                HObject ho_SelectedRegions = null;

                // Local control variables 

                HTuple hv_Number = new HTuple();
                // Initialize local and output iconic variables 
                HOperatorSet.GenEmptyObj(out ho_Rectangle);
                HOperatorSet.GenEmptyObj(out ho_ImageReduced);
                HOperatorSet.GenEmptyObj(out ho_Regions);
                HOperatorSet.GenEmptyObj(out ho_RegionOpening);
                HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
                HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
                HOperatorSet.GenEmptyObj(out ho_Rectangle1);
                HOperatorSet.GenEmptyObj(out ho_Rectangle2);

                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, row, col, phi,lenth1, lenth2);
                HOperatorSet.SetColor(hv_win1, "red");
                HOperatorSet.SetDraw(hv_win1, "margin");
                HOperatorSet.DispObj(ho_Rectangle, hv_win1);
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(image, ho_Rectangle, out ho_ImageReduced);
                {
                    //
                    short ret = 0;
                    plc1.ReadDeviceRandom2(In9, 1, out ret);
                    if (ret == 8)
                    {
                        ho_Rectangle1.Dispose();
                        HOperatorSet.GenRectangle1(out ho_Rectangle1, row1Card1, col1Card1, row2Card1, col2Card1);
                        HOperatorSet.OverpaintRegion(ho_ImageReduced, ho_Rectangle1, 0, "fill");

                        ho_Rectangle2.Dispose();
                        HOperatorSet.GenRectangle1(out ho_Rectangle2, row1Card2, col1Card2, row2Card2, col2Card2);
                        HOperatorSet.OverpaintRegion(ho_ImageReduced, ho_Rectangle2, 0, "fill");
                    }
                    //
                }
                ho_Regions.Dispose();
                HOperatorSet.Threshold(ho_ImageReduced, out ho_Regions, threshold, 255);
                ho_RegionOpening.Dispose();
                HOperatorSet.OpeningCircle(ho_Regions, out ho_RegionOpening, 3.5);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_RegionOpening, out ho_ConnectedRegions);
                ho_SelectedRegions.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area","and", min_area, 99999999);
                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if (hv_Number>0)
                {
                    HOperatorSet.SetDraw(hv_win1, "fill");
                    HOperatorSet.DispObj(ho_SelectedRegions, hv_win1);
                    ////
                    //caer = (hv_Number == 2 &&
                    //        Caer(ho_SelectedRegions, row1Card1, col1Card1, row2Card1, col2Card1, minareaCard1, maxareaCard1)&&
                    //        Caer(ho_SelectedRegions, row1Card2, col1Card2, row2Card2, col2Card2, minareaCard2, maxareaCard2)&&
                    //        b_model);
                    ////
                }
                ho_Rectangle.Dispose();
                ho_Rectangle1.Dispose();
                ho_Rectangle2.Dispose();
                ho_ImageReduced.Dispose();
                ho_Regions.Dispose();
                ho_RegionOpening.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_SelectedRegions.Dispose();
                if (hv_Number==0 && !b_model)
                {
                    return "OK";
                }
                else
                {
                    SaveImage("NG", image);
                    return "NG";
                }

            }
            catch 
            {
                SaveImage("Catch", image);
                return "NG";
            }
        }
        private bool Caer(HObject hoj, HTuple hv_Number, HTuple hv_row1, HTuple hv_col1, HTuple hv_row2, HTuple hv_col2, HTuple minarea, HTuple maxarea)
        {
            try
            {
                HTuple hv_area = null, hv_col = null, hv_row = null;
                HOperatorSet.AreaCenter(hoj, out hv_area, out hv_row, out hv_col);

                for (int i = 0; i < hv_Number; i++)
                {
                    if (hv_area[i] < maxarea &&
                        hv_row[i] > hv_row1 && hv_row[i] < hv_row2 && hv_col[i] > hv_col1 && hv_col[i] < hv_col2)
                    {

                    }
                }


                if ((hv_area[0] > minarea && hv_area[0] < maxarea &&hv_row[0] > hv_row1 && hv_row[0] < hv_row2 &&hv_col[0] > hv_col1 && hv_col[0] < hv_col2)
                    ||
                    (hv_area[1] > minarea && hv_area[1] < maxarea && hv_row[1] > hv_row1 && hv_row[1] < hv_row2 && hv_col[1] > hv_col1 && hv_col[1] < hv_col2))
                {
                    //面积/位置ok
                    return true;
                }
            }
            catch
            {
            }
            return false;
        }
        private bool Caer(HObject hoj, HTuple hv_row1, HTuple hv_col1, HTuple hv_row2, HTuple hv_col2, HTuple minarea, HTuple maxarea)
        {
            try
            {
                HTuple hv_area = null, hv_col = null, hv_row = null;
                HOperatorSet.AreaCenter(hoj, out hv_area, out hv_row, out hv_col);

                if ((hv_area[0] > minarea && hv_area[0] < maxarea && hv_row[0] > hv_row1 && hv_row[0] < hv_row2 && hv_col[0] > hv_col1 && hv_col[0] < hv_col2)
                    ||
                    (hv_area[1] > minarea && hv_area[1] < maxarea && hv_row[1] > hv_row1 && hv_row[1] < hv_row2 && hv_col[1] > hv_col1 && hv_col[1] < hv_col2))
                {
                    //面积/位置ok
                    return true;
                }
            }
            catch
            {
            }
            return false;
        }
        #region MyRegion
        private bool Find_Model(HObject image)
        {

            try
            {
                // Local iconic variables 

                // Local control variables 
                HObject ho_Rectangle = null, ho_ImageReduced = null;
                HTuple hv_ModelID = null, hv_Row = null, hv_Column = null;
                HTuple hv_Angle = null, hv_Scale = null, hv_Score = null;

                HOperatorSet.GenEmptyObj(out ho_ImageReduced);
                HOperatorSet.GenEmptyObj(out ho_Rectangle);
                ho_Rectangle.Dispose();
                ho_ImageReduced.Dispose();
                HOperatorSet.GenRectangle1(out ho_Rectangle, 750, 1800, 2600, 2400);
                HOperatorSet.ReduceDomain(image, ho_Rectangle, out ho_ImageReduced);
                // Initialize local and output iconic variables 
                HOperatorSet.ReadShapeModel("modelA.shm", out hv_ModelID);
                HOperatorSet.FindScaledShapeModel(ho_ImageReduced, hv_ModelID, -0.39,
                    0.78, 0.9, 1.1, 0.7, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column,
                    out hv_Angle, out hv_Scale, out hv_Score);
                HOperatorSet.ClearShapeModel(hv_ModelID);

                ho_Rectangle.Dispose();
                ho_ImageReduced.Dispose();
                if (hv_Score.Length > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {

                return true;
            }

        }
        #endregion
        private bool Find_Model_(HObject image)
        {

            try
            {
                // Local iconic variables 

                // Local control variables 

                HTuple hv_ModelID = null, hv_Row = null, hv_Column = null;
                HTuple hv_Angle = null, hv_Scale = null, hv_Score = null;
                // Initialize local and output iconic variables 
                HOperatorSet.ReadShapeModel("modelA.shm", out hv_ModelID);
                HOperatorSet.FindScaledShapeModel(image, hv_ModelID, -0.39,
                    0.78, 0.9, 1.1, 0.7, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column,
                    out hv_Angle, out hv_Scale, out hv_Score);
                HOperatorSet.ClearShapeModel(hv_ModelID);
                if (hv_Score.Length>0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {

                return true;
            }

        }

        private void Box_Confirm(object sender, EventArgs e)
        {
            Scanner_Box_Confirm.ComPortDataSend("16 54 0D", true, true);
        }
        private void sfcs(string ss)
        {
            WZS_SFCS.clsInfoNameValue[] a = { };
            Mes.GetKeyInfoFromView("FPW83829NRHL36T2L", "PO", "15", ref a);
            InsertNote(ss+a[0].InfoValue.ToString(), listBox1);
            WZS_SFCS.clsInfoNameValue[] b = { };
            Mes.GetKeyInfoFromView("FPW91163RC5L854AX", "PO", "15", ref b);
            InsertNote(ss + b[0].InfoValue.ToString(), listBox1);
        }

        private void t1()
        {
            while(true)
            {
                //Thread.Sleep(10);
                sfcs("t1");
            }
        }

        private void t2()
        {
            while (true)
            {
                //Thread.Sleep(10);
                sfcs("t2");
            }
        }

        private void Auto()
        {
            b_auto_thread = true;
            while(b_auto_thread)
            {
                Thread.Sleep(100);

                short ret_In8;
                if (plc1.ReadDeviceRandom2(In8, 1, out ret_In8) == 0)
                {
                    if (ret_In8==1)
                    {
                        result_detection.Clear();
                        result_code.Clear();
                        result_type.Clear();
                        result_weight.Clear();
                        result_type_out.Clear();
                        Mark_Weight = "Ready";
                        Mark_BoxConfirm = "Ready";
                        try
                        {
                            T_Final_Weighing.Abort();
                            T_Entrance_Scan.Abort();
                            T_Detection.Abort();
                            T_Seperate_Scan.Abort();
                            T_Front_Weighing.Abort();
                            T_Export_Scan.Abort();
                            T_Check_Box_Label.Abort();
                        }
                        catch
                        {

                        }
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In8, 1, ref ret1);
                        InsertNote(In8 + "——清计数完成", listBox1);
                    }
                }

                //入口处扫码
                short ret_In0;
                if (plc1.ReadDeviceRandom2(In0, 1, out ret_In0) == 0)
                {
                    if (ret_In0 == 1)
                    {
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In0, 1, ref ret1);
                        InsertNote(In0+"——入口处扫码", listBox1);

                        T_Entrance_Scan = new Thread(new ThreadStart(Entrance_Scan));
                        T_Entrance_Scan.Start();
                    }
                }


                //异物检测拍照
                short ret_In1;
                if (plc1.ReadDeviceRandom2(In1, 1, out ret_In1) == 0)
                {
                    if (ret_In1 == 1)
                    {
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In1, 1, ref ret1);
                        InsertNote(In1+"——异物检测", listBox1);

                        T_Detection = new Thread(new ThreadStart(Detection));
                        T_Detection.Start();

                    }
                }
                str_result_detection = string.Join(",", result_detection.ToArray());
                lab_detection.Text = result_detection.Count.ToString() + ":" + str_result_detection;
                OperateIniFile.WriteIniData("在籍", "detection", str_result_detection, Application.StartupPath + @"\Tool\Setting.ini");



                //人工段来料分板扫码
                short ret_In2;
                if (plc1.ReadDeviceRandom2(In2, 1, out ret_In2) == 0)
                {
                    if (ret_In2 != 0)
                    {
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In2, 1, ref ret1);
                        InsertNote(In2+"——人工段来料分板扫码", listBox1);

                        T_Seperate_Scan = new Thread(new ThreadStart(Seperate_Scan));
                        T_Seperate_Scan.Start();

                    }
                }
                str_result_code = string.Join(",", result_code.ToArray());
                tb_code.Text = result_code.Count.ToString() + ":" + str_result_code;
                str_result_type = string.Join(",", result_type.ToArray());
                tb_type.Text = result_type.Count.ToString() + ":" + str_result_type;
                OperateIniFile.WriteIniData("在籍", "code", str_result_code, Application.StartupPath + @"\Tool\Setting.ini");
                OperateIniFile.WriteIniData("在籍", "type", str_result_type, Application.StartupPath + @"\Tool\Setting.ini");



                //// 自动段来料称总重
                //short ret_In3;
                //if (plc1.ReadDeviceRandom2(In3, 1, out ret_In3) == 0)
                //{
                //    if (ret_In3 == 1)
                //    {
                //        short ret1 = 0;
                //        plc1.WriteDeviceRandom2(In3, 1, ref ret1);
                //        InsertNote(In3+"——自动段来料称总重");

                //        Thread.Sleep(1000);

                //        short ret2 = 1;
                //        plc1.WriteDeviceRandom2(Out3, 1, ref ret2);
                //        InsertNote(Out3+"——反馈自动段来料称总重完成");

                //    }
                //}

                //前称重

                lab_Weight1.Text = Scales1.ReceiveData.Split(' ')[0];
                //手动段来料分板称重
                short ret_In4;
                if (plc1.ReadDeviceRandom2(In4, 1, out ret_In4) == 0)
                {
                    if (ret_In4 != 0)
                    {
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In4, 1, ref ret1);
                        InsertNote(In4+"——手动段来料分板称重", listBox1);

                        T_Front_Weighing = new Thread(new ParameterizedThreadStart (Front_Weighing));
                        T_Front_Weighing.Start(ret_In4);

                        
                    }
                }
                str_result_weight = string.Join(",", result_weight.ToArray());
                lab_weight.Text = result_weight.Count.ToString() + ":" + str_result_weight;
                str_result_detection = string.Join(",", result_detection.ToArray());
                lab_detection.Text = result_detection.Count.ToString() + ":" + str_result_detection;
                str_result_code = string.Join(",", result_code.ToArray());
                tb_code.Text = result_code.Count.ToString() + ":" + str_result_code;
                str_result_type = string.Join(",", result_type.ToArray());
                tb_type.Text = result_type.Count.ToString() + ":" + str_result_type;
                OperateIniFile.WriteIniData("在籍", "detection", str_result_detection, Application.StartupPath + @"\Tool\Setting.ini");
                OperateIniFile.WriteIniData("在籍", "code", str_result_code, Application.StartupPath + @"\Tool\Setting.ini");
                OperateIniFile.WriteIniData("在籍", "type", str_result_type, Application.StartupPath + @"\Tool\Setting.ini");
                OperateIniFile.WriteIniData("在籍", "weight", str_result_weight, Application.StartupPath + @"\Tool\Setting.ini");


                //出口处扫码
                short ret_In5;
                if (plc1.ReadDeviceRandom2(In5, 1, out ret_In5) == 0)
                {
                    if (ret_In5 == 1)
                    {
                        short ret1 = 0;
                        plc1.WriteDeviceRandom2(In5, 1, ref ret1);
                        InsertNote(In5+"——异常排料前扫码", listBox1);

                        T_Export_Scan = new Thread(new ThreadStart(Exprot_Scan));
                        T_Export_Scan.Start();
                    }
                }
                str_result_type_out = string.Join(";", result_type_out.ToArray());
                tb_type_out.Text = result_type_out.Count.ToString() + ":" + str_result_type_out;
                OperateIniFile.WriteIniData("在籍", "type_out", str_result_type_out, Application.StartupPath + @"\Tool\Setting.ini");


                //后称重

                lab_Weight2.Text = Scales2.ReceiveData.Split(' ')[0];
                //异常排料后称总重
                short ret_In6;
                if (plc1.ReadDeviceRandom2(In6, 1, out ret_In6) == 0)
                {
                    if (ret_In6 == 1&& Mark_Weight=="Ready"&&Mark_BoxConfirm=="Ready")
                    {
                        Mark_Weight = "Operating";
                        short ret5 = 0;
                        plc1.WriteDeviceRandom2(In6, 1, ref ret5);
                        InsertNote(In6+"——异常排料后称总重", listBox1);

                        T_Final_Weighing = new Thread(new ThreadStart(Final_Weighing));
                        T_Final_Weighing.Start();

                    }
                }
                str_result_type_out = string.Join(";", result_type_out.ToArray());
                tb_type_out.Text = result_type_out.Count.ToString() + ":" + str_result_type_out;
                OperateIniFile.WriteIniData("在籍", "type_out", str_result_type_out, Application.StartupPath + @"\Tool\Setting.ini");

                if (Mark_Weight=="Operating"&&Mark_BoxConfirm=="Operating")
                {
                    if (Scanner_Box_Confirm.ReceiveData!="")
                    {
                        if (Scanner_Box_Confirm.ReceiveData.Contains(Check_Box_Type(Out_Type)))
                        {
                            short ret = 0; 
                            short ret1 = 0;
                            plc3.WriteDeviceRandom2(POut2, 1, ref ret);      //扫箱子码OK灭掉
                            plc3.WriteDeviceRandom2(POut3, 1, ref ret1);
                            InsertNote("箱子校验成功,箱子料号为:" + Scanner_Box_Confirm.ReceiveData, listBox1);
                            Mark_Weight = "Ready";
                            Mark_BoxConfirm = "Ready";
                            Out_Type = "";
                            Scanner_Box_Confirm.ReceiveData = "";
                        }
                        else
                        {
                            short ret = 1;
                            short ret1 = 1;
                            plc3.WriteDeviceRandom2(POut2, 1, ref ret);      //扫箱子码NG
                            plc3.WriteDeviceRandom2(POut3, 1, ref ret1);
                            Scanner_Box_Confirm.ReceiveData = "";
                        }
                    }

                }

                short ret_PIn1;
                if (plc3.ReadDeviceRandom2(PIn1,1,out ret_PIn1)==0)
                {
                    if (ret_PIn1==1)
                    {
                        short ret = 0;
                        plc3.WriteDeviceRandom2(PIn1, 1, ref ret);
                        InsertNote("箱子Label检查有无",listBox1);
                        T_Check_Box_Label = new Thread(new ThreadStart(Check_Box_Label));
                        T_Check_Box_Label.Start();
                    }
                }

                OperateIniFile.WriteIniData("在籍", "Product_Num", string.Join(",",Product_Num), Application.StartupPath + @"\Tool\Setting.ini");
                label14.Text = string.Format("OK:{0},异物:{1},条码ng:{2},错站:{3},被hold:{4},混料:{5},重量异常:{6},没checkout:{7},库类错误:{8},在库标志:{9},CQA BL:{10},X17_Tilt_NG:{11}", Product_Num[0], Product_Num[1], Product_Num[2], Product_Num[3], Product_Num[4], Product_Num[5], Product_Num[6], Product_Num[7],Product_Num[8], Product_Num[9], Product_Num[10], Product_Num[11]);

                short storage1, storage2, storage3, storage4, storage5, storage6;
                storage1 = (short)(cb_storage1.SelectedIndex + 1);
                storage2 = (short)(cb_storage2.SelectedIndex + 1);
                storage3 = (short)(cb_storage3.SelectedIndex + 1);
                storage4 = (short)(cb_storage4.SelectedIndex + 1);
                storage5 = (short)(cb_storage5.SelectedIndex + 1);
                storage6 = (short)(cb_storage6.SelectedIndex + 1);

                int a = plc2.WriteDeviceRandom2("D600", 1, ref storage1);
                int b = plc2.WriteDeviceRandom2("D601", 1, ref storage2);
                int c = plc2.WriteDeviceRandom2("D602", 1, ref storage3);
                int d = plc2.WriteDeviceRandom2("D603", 1, ref storage4);
                int e = plc2.WriteDeviceRandom2("D604", 1, ref storage5);
                int f = plc2.WriteDeviceRandom2("D605", 1, ref storage6);

                short packagemode = (short)(cb_packagemode.SelectedIndex);
                plc1.WriteDeviceRandom2(Out8, 1, ref packagemode);

                label13.Text = Mark_Weight+","+Mark_BoxConfirm;
                if (result_code.Count>24||result_detection.Count>14||result_type.Count>24||result_weight.Count>11||result_type_out.Count>4)
                {
                    InsertNote("计数错误！"+"拍照："+result_detection.Count.ToString()+ "条码：" + result_code.Count.ToString()+ "类型：" + result_type.Count.ToString()+ "称重：" + result_weight.Count.ToString()+ "出口处物料：" + result_type_out.Count.ToString(),listBox1);
                    Auto_Thread.Abort();
                    MessageBox.Show("计数错误！请重启软件，复位清料再启动！！！");
                }
            }
        }
    }
}
